package examsrv

import (
	"strconv"

	"gitee.com/chuanjinge/gopkgserv/api/response"
	"gitee.com/chuanjinge/gopkgserv/internal/dao"
)

type ExamRecordItem struct {
	ExamID   int
	Correct  int
	Total    int
	ExamTime string
}

// GetExamRecords 分页查询考试记录及统计
func GetExamRecords(userId int64, pageStr, pageSizeStr string) ([]response.ExamRecordItem, int, error) {
	page, _ := strconv.Atoi(pageStr)
	pageSize, _ := strconv.Atoi(pageSizeStr)
	if page < 1 {
		page = 1
	}
	if pageSize < 1 {
		pageSize = 20
	}
	offset := (page - 1) * pageSize
	var exams []dao.ExamExams
	var total int64
	if err := dao.DB.Model(&dao.ExamExams{}).Where("user_id = ?", userId).Count(&total).Error; err != nil {
		return nil, 0, err
	}
	if err := dao.DB.Where("user_id = ?", userId).Order("created_at desc").Offset(offset).Limit(pageSize).Find(&exams).Error; err != nil {
		return nil, int(total), err
	}
	var list []response.ExamRecordItem
	for _, exam := range exams {
		correct, totalQ := getExamCorrectAndTotal(exam.ID)
		// 提交时间有可能是空的，所以要预防性处理
		var examTime string
		if exam.FinishedAt != nil {
			examTime = exam.FinishedAt.Format("2006-01-02 15:04:05")
		} else {
			examTime = ""
		}
		item := response.ExamRecordItem{
			ExamID:   exam.ID,
			Correct:  correct,
			Total:    totalQ,
			ExamTime: examTime,
		}
		list = append(list, item)
	}
	return list, int(total), nil
}

// getExamCorrectAndTotal 查询考试答对数量和总题数（示例实现）
func getExamCorrectAndTotal(examId int) (correct, total int) {
	// 实际应统计 exam_user_answers 表
	return 10, 15 // 示例：答对10，总题数15
}
